/*
 * @Author: wangjh wangjiahui0710@163.com
 * @Date: 2024-06-11 18:09:29
 * @LastEditors: wangjh wangjiahui0710@163.com
 * @LastEditTime: 2024-06-12 17:08:59
 * @FilePath: \cip-mobile\src\stores\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { apiLogin } from '@/genapi/login';
import type { components } from '@/genapi/wh';
import { whManagerSystemSystemUserGetCurrUserInfoUsingGet } from '@/genapi/wh';

export const useUserStore = defineStore('user', () => {
	// token
	const authorization = useLocalStorage('authorization', localStorage.getItem('authorization') || '');
	const router = useRouter();

	// 当前是否已登录
	const isLogined = computed(() => {
		return !!authorization.value;
	});

	const login = async (username: string, password: string) => {
		const { data } = await apiLogin({ username, password });
		authorization.value = data?.accessToken ?? '';
	};

	const logout = () => {
		authorization.value = '';
		router.replace({ path: '/login' });
	};

	const userInfo = shallowRef<components['schemas']['LoginUserInfoDTO'] & Record<string, any>>();

	/**
	 *  用户类型：1-企业用户 2-园区用户 3-第三方单位ID
	 */
	const userType = computed<'1' | '2' | '3' | undefined>(() => {
		const type = userInfo.value?.systemUser?.type;
		return type?.toString() as '1' | '2' | '3' | undefined;
	});

	const getUserInfo = async () => {
		const { data = {} } = await whManagerSystemSystemUserGetCurrUserInfoUsingGet({});
		userInfo.value = data;
	};

	watchImmediate(authorization, (authorization) => {
		if (authorization) {
			getUserInfo();
		} else {
			userInfo.value = {};
			logout();
		}
	});
	const articleId = ref('');
  const specialOperateId = ref('')

	const examDetails = ref<any>({});

	return {
		authorization,
		isLogined,
		login,
		logout,
		userInfo,
		userType,
		getUserInfo,
		articleId,
    specialOperateId,
		examDetails,
	};
});
